<?php
/***
* +----------------------------------------------------------------------+
* | DATE: 2008-5-15                                                      |
* +----------------------------------------------------------------------+
* | Author: YuYii <fin1983@Hotmail.com>                                  |
* +----------------------------------------------------------------------+
*/

if (!isset($_GET['action'])) {
	header("HTTP/1.1 403 Forbidden");
	exit();
}

include("../class/operation.php");

$types_c = new types;
switch($_GET['action']) {
	case "getCostType":
		$types_c->getCostType();break;
	case "setCostType":
		$types_c->setCostType();break;

}

class types {

	//特殊数组处理，同下述方法
	function arr2jsArr_($arr) {
		if (empty($arr) || count($arr) == 0) {
			return null;
		}
		$jsArr = "[";
		foreach($arr as $v) {
			if ($jsArr != "[")
				$jsArr .= ",";
			$jsArr .= "['";
			$belong = $v['belong'] == 'out'?'支出':($v['belong'] == 'in'?'收入':'外债');
			$jsArr .= $v['type_id']."','".$v['type_name']."','".$v['description']."','".$belong;
			$jsArr .= "']";
		}
		$jsArr .= "]";
		return $jsArr;
	}

	function checkdelData(&$data) {
		$del = substr($_POST['delData'],1,-1);
		$del = explode(",",$del);
		if (empty($del)) return false;
		foreach($del as $v){
			if (empty($data))
				$data = substr($v,1,-1);
			else {
				$data .= ",";
				$data .= substr($v,1,-1);
			}
		}
		return true;
	}

	function getCostType() {
		$act = new Operation;
		if (isset($_POST['doing']) && $_POST['doing'] == 'deldata') {
			if ($this->checkdelData($data))
				$act->delTypes($data);
		}
		$t = array('out','in','debt');
		if (isset($_GET['belong']) && in_array($_GET['belong'],$t)) {
			$rs = $act->getTypes($_GET['belong']);
		}
		else $rs = $act->getTypes();
		$jsArr = $this->arr2jsArr_($rs);
		header("Content-type: text/html; charset=UTF-8");
		echo $jsArr;
	}

	function setCostType() {
		if (!isset($_POST['id']) || !isset($_POST['type']) || !isset($_POST['desc'])) {
			exit();
		}
		$act = new Operation;

		$belong = array('out','in','debt');
		if (!in_array($_POST['belong'],$belong)) {
			echo "{'errorInfo':'保存失败，提交数据不合法。'}";
		}
		else {
			if ($act->setTypes($_POST['id'],$_POST['type'],$_POST['desc'],$_POST['belong']))
				echo "{'success':'ok','info':'数据保存成功!'}";
			else echo "{'errorInfo':'保存失败，数据库写入错误。'}";
		}
	}

}

?>